package ws

import (
	"gitee.com/chenhonghua/ginorigin/log"
)

var (
	manager = connManager{
		broadcast:  make(chan Message),
		register:   make(chan websocketConnection),
		unregister: make(chan websocketConnection),
		pool:       map[string]websocketConnection{},
	}
)

type connManager struct {
	pool       map[string]websocketConnection
	register   chan websocketConnection
	unregister chan websocketConnection
	broadcast  chan Message
}

func (manager connManager) getConn(id string) websocketConnection {
	return manager.pool[id]
}

var (
	connectNotice    []byte = []byte("/A new socket has connected.")
	disconnectNotice []byte = []byte("/A socket has disconnected.")
)

func (manager connManager) work() {
	for {
		select {
		case conn := <-manager.register:
			log.Debugf("订阅ws连接：%#v", conn)
			manager.pool[conn.id] = conn
			conn.sendContent <- connectNotice // 通知订阅成功
		case conn := <-manager.unregister:
			if _, ok := manager.pool[conn.id]; !ok { // 避免重复
				continue
			}
			log.Debugf("注销ws连接：%#v", conn)
			conn.sendContent <- connectNotice // 通知注销订阅
			conn.socket.Close()
			delete(manager.pool, conn.id)
		case message := <-manager.broadcast:
			// 当收到广播时，将消息推送给指定订阅者
			for _, r := range message.Recipients {
				conn := manager.getConn(r)
				select {
				case conn.sendContent <- message.Content:
				default:
					close(conn.sendContent)
					delete(manager.pool, conn.id)
				}
			}
		}
	}
}
